'''
MIT License

Copyright (c) 2016 Kevin Albertson
Copyright (c) 2023 Anggara Yama Putra

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
_ILLEGALS = (
    0, # null
    10, # newline
    13, # carriage return
    34, # double quote
    38, # ampersand
    92, # backslash
)
_SHORTENED = 0b111
'''Uses the illegal index to signify the last two-byte char encodes <= 7 bits.'''


# For debugging.
def _to_7_bits (
    num: int,
) -> str:
    str2: str = bin( num )[2:]
    return ('0000000')[len(str2)-1] + str2


def _unsigned_rshift (
    val: int,
    count: int,
) -> int:
    return ((val % 0x100000000) >> count)


def encode (
    rawData: bytes|bytearray|str,
) -> bytearray:
    outData = bytearray()
    curIndex = 0
    curBit = 0 # Points to current bit needed

    if type(rawData) is str:
        rawData = rawData.encode( 'utf8' )

    # Get seven bits of input data. Returns false if there is no input left.
    def __get7 ():
        nonlocal rawData, curIndex, curBit
        length = len(rawData)
        if curIndex >= length:
            return None
        # Shift, mask, unshift to get first part.
        firstByte = rawData[curIndex]
        firstPart = (_unsigned_rshift(0b11111110, curBit) & firstByte) << curBit
        # Align it to a seven bit chunk.
        firstPart >>= 1
        # Check if we need to go to the next byte for more bits.
        curBit += 7
        if curBit < 8:
            # Do not need next byte.
            return firstPart
        curBit -= 8
        curIndex += 1
        # Now we want bits [0..curBit] of the next byte if it exists.
        if curIndex >= length:
            return firstPart
        secondByte = rawData[curIndex]
        secondPart = (_unsigned_rshift(0xFF00, curBit) & secondByte) & 0xFF
        # Align it.
        secondPart >>= (8 - curBit)
        return firstPart | secondPart

    # Grab 7 bits.
    while (bits := __get7()) is not None:
        #print( 'Seven input bits', _to_7_bits(bits), bits )
        try:
            illegalIndex = _ILLEGALS.index( bits )
        except ValueError:
            outData.append( bits )
        else:
            # Since this will be a two-byte character, get the next chunk of seven bits.
            nextBits = __get7()
            #print( 'Handle illegal sequence', _to_7_bits(bits), _to_7_bits(nextBits) )

            b1, b2 = 0b11000010, 0b10000000
            if nextBits is None:
                #print( 'Last seven bits are an illegal sequence.' )
                b1 |= (0b111 & _SHORTENED) << 2
                nextBits = bits # Encode these bits after the shortened signifier.
            else:
                b1 |= (0b111 & illegalIndex) << 2

            # Push first bit onto first byte, remaining 6 onto second.
            firstBit = 1 if (nextBits & 0b01000000 > 0) else 0
            b1 |= firstBit
            b2 |= nextBits & 0b00111111
            outData.extend( [b1, b2] )
    return outData


def decode (
    strData: bytes|bytearray|str,
) -> bytearray:
    if type(strData) is not str:
        strData = strData.decode( 'utf8' )

    decoded = bytearray()
    curByte = bitOfByte = 0

    def __push7 (byte):
        nonlocal decoded, curByte, bitOfByte
        byte <<= 1
        # Align this byte to offset for current byte.
        curByte |= _unsigned_rshift(byte, bitOfByte)
        bitOfByte += 7
        if bitOfByte >= 8:
            decoded.append( curByte )
            bitOfByte -= 8
            # Now, take the remainder, left shift by what has been taken.
            curByte = (byte << (7 - bitOfByte)) & 255

    for s in strData:
        c = ord( s )
        # Check if this is a two-byte character.
        if c > 127:
            # Note, the charCodeAt will give the codePoint, thus
            # 0b110xxxxx 0b10yyyyyy will give => xxxxxyyyyyy
            illegalIndex = _unsigned_rshift(c, 8) & 7 # 7 = 0b111.
            # We have to first check if this is a shortened two-byte character, i.e. if it only
            # encodes <= 7 bits.
            if illegalIndex != _SHORTENED:
                __push7( _ILLEGALS[illegalIndex] )

            # Always push the rest.
            __push7( c & 127 )
        else:
        # One byte characters can be pushed directly.
            __push7( c )
    return decoded


def encode_as_str  (
    rawData: bytes|bytearray|str,
) -> str:
    return encode(rawData).decode('utf8')


def decode_as_str  (
    strData: bytes|bytearray|str,
    **kwargs,
) -> str:
    return decode(strData).decode(**kwargs)
